package top.ljjapp.controller;/**
 * @FileName: FileController.java
 * @Package: top.ljjapp.controller
 * @Author: lijiajun
 * <br/>
 * @Created: 2018/11/21 14:32
 */

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.ljjapp.dto.FileInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * <p></p>
 * <p/>
 * <PRE>
 * <BR> 修改记录
 * <BR>-----------------------------------------------
 * <BR> 修改日期 修改人 修改内容
 * </PRE>
 *
 * @author lijiajun
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    private String folder = "D:\\Project\\IdeaProject\\gitee\\security\\mydemo\\src\\main\\java\\top\\ljjapp\\controller";

    @PostMapping
    @ApiOperation(value = "上传文件")
    public FileInfo upload(@ApiParam(value = "上传的文件") MultipartFile file) throws IOException {
        log.info(file.getName());
        log.info(file.getOriginalFilename());
        log.info(String.valueOf(file.getSize()));

        File localFile = new File(folder, new Date().getTime() + ".txt");
        file.transferTo(localFile);

        return new FileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "下载文件")
    public void download(
            @ApiParam(value = "下载文件的名称")@PathVariable String id,
            HttpServletRequest request,
            HttpServletResponse response){
        try (
            InputStream inputStream = new FileInputStream(new File(folder, id+"txt"));
            OutputStream outputStream = response.getOutputStream()){
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (Exception e){

        }
    }
}